package com.aceleeyy.apb.base;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * API-响应对象
 *
 * @author Ace Lee
 * @version 1.0
 * @date 2020/8/10 10:41
 **/
@Data
@Builder
@AllArgsConstructor
public class R<T> implements Serializable {

    /**
     * 100000成功，非100000失败
     **/
    @ApiModelProperty(value = "响应码（100000成功）",example = "100000")
    private int status = ApbStatus.SUCCESS.code();

    /**
     * 返回详情
     */
    @ApiModelProperty(value = "响应描述",example = "请求成功!")
    private String message = ApbStatus.SUCCESS.desc();

    /**
     * 返回内容
     */
    @ApiModelProperty("响应内容")
    protected T data;

    private R() {
    }

    public static R custom() {
        return new R();
    }

    public R success(T data) {
        this.data = data;
        return this;
    }

    public R success() {
        this.status = ApbStatus.SUCCESS.code();
        this.message = ApbStatus.SUCCESS.desc();
        return this;
    }

    public R isSuccess(boolean bool) {
        if (bool) {
            this.status = ApbStatus.SUCCESS.code();
            this.message = ApbStatus.SUCCESS.desc();
        } else {
            this.status = ApbStatus.FAIL.code();
            this.message = ApbStatus.FAIL.desc();
        }
        return this;
    }

    public R fail(Integer status, String message) {
        this.status = status;
        this.message = message;
        return this;
    }

    public R fail(ApbStatus apbStatus) {
        this.status = apbStatus.code();
        this.message = apbStatus.desc();
        return this;
    }

    public R fail(String message) {
        this.status = ApbStatus.FAIL.code();
        this.message = message;
        return this;
    }

    public R fail() {
        this.status = ApbStatus.FAIL.code();
        this.message = ApbStatus.FAIL.desc();
        return this;
    }

    public R put(String key, Object value) {
        if (this.getData() == null) {
            Map map = new HashMap();
            map.put(key, value);
            this.data = (T) map;
        } else {
            Map map = (Map) this.getData();
            map.put(key, value);
        }
        return this;
    }
}